package com.iias.common.constants.content;

import com.iias.common.util.log.LogUtils;
import org.slf4j.Logger;

import java.util.LinkedHashMap;
import java.util.List;

/**
 * 进程上下文
 */
public class ProcessContext {

    private static final Logger log = LogUtils.getLogger();
    /**
     * 线程号 对应 数据
     */
    private static final LinkedHashMap<Long,TreadContent> LINKED_HASH_MAP = new LinkedHashMap<Long,TreadContent>();

//    static {
//        Thread thread = Thread.currentThread();
//        new Thread(() -> {
//            log.info(" 线程监听已启动!!!");
//            while (true){
//                try {
//                    Thread.sleep(100);
//                    if (thread.getState() == TERMINATED)break;
//
//                    for (Long key : LINKED_HASH_MAP.keySet()) {
//                        ThreadMXBean tmx = ManagementFactory.getThreadMXBean();
//                        ThreadInfo info = tmx.getThreadInfo(key);
//                        if (info == null ||info.getThreadState() ==TERMINATED)
//                            LINKED_HASH_MAP.remove(key);
//                    }
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//            }
//        }).start();
//    }


    public static void add(Object...objs){
        long id = Thread.currentThread().getId();
        TreadContent treadContent = LINKED_HASH_MAP.get(id);
        if (treadContent == null){
            treadContent = new TreadContent();
            LINKED_HASH_MAP.put(id,treadContent);
        }
        treadContent.add(objs);
    }


    public static void clean(){
        long id = Thread.currentThread().getId();
        LINKED_HASH_MAP.remove(id);
    }


    public static void addAttributes(String key,Object value){
        long id = Thread.currentThread().getId();
        TreadContent treadContent = LINKED_HASH_MAP.get(id);
        if (treadContent == null){
            treadContent = new TreadContent();
            LINKED_HASH_MAP.put(id,treadContent);
        }
        treadContent.setAttributes(key,value);
    }

    public static <T> T getAttributes(String key){
        long id = Thread.currentThread().getId();
        TreadContent treadContent = LINKED_HASH_MAP.get(id);
        if (treadContent == null)return null;
        return treadContent.getAttribute(key);
    }

    public static List<Object> all(){
        TreadContent treadContent = LINKED_HASH_MAP.get(Thread.currentThread().getId());
        if (treadContent==null)return null;
        return treadContent.all();
    }

    public static<T> T getObj(Class<T> t){
        List<Object> all = all();
        if (all == null ) return null;
        for (Object o : all) {
            if (t.isAssignableFrom(o.getClass())){
                return (T) o;
            }
        }
        return null;
    }
}
